package com.fubowen.lepton.ui.container.children.bookmark

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.Fragment
import androidx.navigation.NavController
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.fubowen.lepton.R
import com.fubowen.lepton.bean.BookmarkBean
import com.fubowen.lepton.conf.AnnotationConfig
import com.fubowen.lepton.databinding.FragmentBookmarkGroupBinding
import com.fubowen.lepton.helper.DBHelper
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.UUID


class BookmarkGroupFragment : Fragment() {

    private lateinit var controller: NavController
    private lateinit var binding: FragmentBookmarkGroupBinding
    private val args: BookmarkGroupFragmentArgs by navArgs()
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentBookmarkGroupBinding.inflate(layoutInflater, container, false)
        controller = findNavController()
        goBack()
        binding.bookmarkGroupBack.setOnClickListener { goBackImpl() }
        binding.bookmarkGroupSubmit.setOnClickListener {
            val text = binding.bookmarkGroupTitleText.text
            if (text.isNotBlank()) {
                submit(text.toString())
                goBackImpl()
            }
        }
        binding.bookmarkGroupTitleText.requestFocus()
        return binding.root
    }

    private fun submit(title: String) {
        CoroutineScope(Dispatchers.Main).launch {
            val ids = args.ids.split(",").map { it.toInt() }
            val id = DBHelper.db.bookmarkDao().setOrReplace(
                BookmarkBean(
                    type = BookmarkBean.TYPE_FOLDER,
                    title = title,
                    url = UUID.randomUUID().toString(),
                    icon = R.drawable.ic_new_folder_yellow_24dp.toString(),
                    parentId = args.parentId,
                    iconSource = AnnotationConfig.ICON_SOURCE_RESOURCE,
                )
            )
            DBHelper.db.bookmarkDao().put(id.toInt(), ids)
        }
    }

    private fun goBack() {
        val onBackCallback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                goBackImpl()
                isEnabled = false
            }
        }
        requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, onBackCallback)
    }

    private fun goBackImpl() = controller.navigateUp()
}